<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/13
 * Time: 15:27
 */
class WeiXinPay
{
    private $payData;
    private $title;
    private $orderSn;
    private $accountId;
    private $notifyUrl;
    private $ledger;
    private $sslcert_path;
    private $sslkey_path;

    /**
     *构造方法
     * @param array $accountId
     * @param array $orderSn
     * @param string $notifyUrl
     */
    public function __construct($accountId, $orderSn, $title, $notifyUrl = '',$returnUrl = '',$ledger = array())
    {
        $this->accountId = $accountId;
        $this->title = $title;
        $this->orderSn = $orderSn;
        $this->notifyUrl = $notifyUrl ? $notifyUrl : C('site_url') . U('wechat/wechat_pay/notify');
        $this->ledger = $ledger;
    }

    /**
     * 服务窗支付
     * @return array
     */
    public function windowPay()
    {
        // 获取配置数据
        $this->payData = self::getWechatPayData($this->accountId, $this->orderSn);
        wLog(date('Y-m-d H:i:s').' this->payData:'.var_export($this->payData,true)."\r\n",'wechatPay');
        if (empty($this->payData)) {
            return array('status' => 'F', 'message' => '数据错误');
        }

        // 校验数据
        $this->verifyData($this->payData);

        //加载微信支付类
        vendor('Wechat.WechatPay');
        if ($this->payData['is_special'] == 1) {
            $cWechatPay = new WechatPay($this->payData['parentAppid'], $this->payData['parentMchId'], $this->payData['parentKey'], $this->notifyUrl);
            $cWechatPay->setParameter("sub_openid", $this->payData['subOpenid']);
            $cWechatPay->setParameter("sub_appid", $this->payData['subAppid']);
            $cWechatPay->setParameter("sub_mch_id", $this->payData['subMchId']);
            $cWechatPay->setParameter("goods_tag", "xinsheng"); //微信临时活动(校园开学红包补贴活动)
            $cWechatPay->setParameter('spbill_create_ip', getIP());
        } else {
            $cWechatPay = new WechatPay($this->payData['appId'], $this->payData['mchId'], $this->payData['parentKey'], $this->notifyUrl);
            $cWechatPay->setParameter('openid', $this->payData['openId']);
            $cWechatPay->setParameter('appid', $this->payData['appId']);
            $cWechatPay->setParameter('mch_id', $this->payData['mchId']);
            $cWechatPay->setParameter('spbill_create_ip', getIP());
            if($this->ledger){ //分账功能
                $cWechatPay->setParameter('ledger_size', $this->ledger['ledger_size']);
                foreach ($this->ledger['ledger'] as $k=>$v){
                    $cWechatPay->setParameter($v['ledger_account_name'], $v['ledger_account_value']);
                    $cWechatPay->setParameter($v['ledger_type_name'], $v['ledger_type_value']);
                    $cWechatPay->setParameter($v['ledger_amount_name'], $v['ledger_amount_value']);
                }
            }
        }

        $cWechatPay->setParameter("body", $this->payData['orderName']);
        $cWechatPay->setParameter("out_trade_no", $this->payData['orderSn']);
        $cWechatPay->setParameter("total_fee", $this->payData['orderAmount'] * 100);
        $cWechatPay->setParameter("notify_url", $this->notifyUrl);
        $cWechatPay->setParameter("trade_type", "JSAPI");
        $prepayData = $cWechatPay->getPrepayId();
        wLog(date('Y-m-d H:i:s').' prepayData:'.var_export($prepayData,true)."\r\n",'wechatPay');
        if ($prepayData['status'] == 'S') {
            $prepayId = $prepayData['data'];
        } else {
            return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
        }
        $cWechatPay->setPrepayId($prepayId);
        $jsApiParameters = $cWechatPay->getParameters();
        return array('status' => 'S', 'data' => $jsApiParameters);
    }


    /**
     * 二维码支付
     * @return array
     */
    public function codePay()
    {
        $this->payData = self::getWechatPayData($this->accountId, $this->orderSn);
        if (empty($this->payData)) {
            return array('status' => 'F', 'message' => '数据错误');
        }


        //加载微信支付类
        vendor('Wechat.WechatPay');
        if ($this->payData['is_special'] == 1) {
            $cWechatPay = new WechatPay($this->payData['parentAppid'], $this->payData['parentMchId'], $this->payData['parentKey'], $this->notifyUrl);
            $cWechatPay->setParameter("sub_appid", $this->payData['subAppid']);
            $cWechatPay->setParameter("sub_mch_id", $this->payData['subMchId']);

        } else {
            $cWechatPay = new WechatPay($this->payData['appId'], $this->payData['mchId'], $this->payData['parentKey'], $this->notifyUrl);
            $cWechatPay->setParameter('appid', $this->payData['appId']);
            $cWechatPay->setParameter('mch_id', $this->payData['mchId']);
            $cWechatPay->setParameter('spbill_create_ip', getIP());
        }

        $cWechatPay->setParameter('time_start', date("YmdHis"));
        $cWechatPay->setParameter('time_expire', date("YmdHis", time() + 600));
        $cWechatPay->setParameter("body", $this->payData['orderName']);
        $cWechatPay->setParameter("out_trade_no", $this->payData['orderSn']);
        $cWechatPay->setParameter("product_id", rand(100000, 999999));
        $cWechatPay->setParameter("total_fee", $this->payData['orderAmount'] * 100);
        $cWechatPay->setParameter("notify_url", $this->notifyUrl);
        $cWechatPay->setParameter("trade_type", "NATIVE");
        $prepayData = $cWechatPay->getCodeUrl();

        if ($prepayData['status'] == 'S') {
            $prepayCodeUrl = $prepayData['data'];
            return array('status' => 'S', 'data' => $prepayCodeUrl);
        } else {
            return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
        }
    }

    /**
     *微信发红包
     * @param string $openid
     * @param float $money 红包金额
     * @param string $wishing 祝福语
     * @param string $actName 活动名称
     * @param string $remark 备注
     * @return array $res
     */
    public function sendRedToUser($openid, $money, $wishing = '', $actName = '', $remark = '')
    {
        if (!$openid) {
            return array('status' => 'F', 'message' => 'openid不能为空');
        }

        if (!$money || $money < 1) {
            return array('status' => 'F', 'message' => '单个红包金额必须要大于1元');
        }

        if (strlen($wishing) > 128) {
            return array('status' => 'F', 'message' => '祝福语字数超过限制');
        }

        if (strlen($actName) > 32) {
            return array('status' => 'F', 'message' => '活动名称字数超过限制');
        }

        if (strlen($remark) > 256) {
            return array('status' => 'F', 'message' => '备注信息字数超过限制');
        }

        vendor('Wechat.WechatApi');
        $wechat = D('Wechat/Wechat')->getInfo(array('account_id' => $this->accountId));
        $weixin = new WechatApi($wechat['wechat_id']);

        $array['mch_billno'] = $wechat['parent_mch_id'] . date('YmdHis') . mt_rand(1000, 9999);
        $array['mch_id'] = $wechat['parent_mch_id'];
        $array['sub_mch_id'] = $wechat['mch_id'];
        $array['wxappid'] = $wechat['parent_appid'];
        $array['msgappid'] = $wechat['appid'];
        $array['send_name'] = $wechat['wechat_name'];
        $array['re_openid'] = $openid;
        $array['total_amount'] = $money * 100;
        $array['min_value'] = $money * 100;
        $array['max_value'] = $money * 100;
        $array['wishing'] = $wishing ? $wishing : '恭喜发财，大吉大利';
        $array['act_name'] = $actName ? $actName : '红包活动';
        $array['remark'] = $remark ? $remark : '恭喜发财，大吉大利';
        $res = $weixin->send_redpacket($array);
        return $res;
    }

    /**
     *
     * 申请退款
     * @param $accountId
    * @param $refundData 'out_trade_no','total_fee','refund_fee','out_refund_no','op_user_id'
     * @return array $res
     */
    public function refund($accountId, $refundData)
    {
        //检测必填参数
        if (!$this->orderSn) {
            return array('stutus' => 'F', 'message' => '商户订单号不能为空！');
        }
         $account_id = $accountId?$accountId:$this->accountId;
        $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $account_id));
        if (!$wechatInfo) {
            return array('stutus' => 'F', 'message' => '微信配置信息不能为空');
        }

        vendor('Wechat.WxPayNew');
        $inputObj = new WxPayRefund();
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        $orderSn = $refundData['out_trade_no']?$refundData['out_trade_no']:$this->orderSn;
        $inputObj->SetOut_trade_no($orderSn);
        $this->sslcert_path = $wechatInfo['sslcert_path'];
        $this->sslkey_path = $wechatInfo['sslkey_path'];
        if ($wechatInfo['is_special']) {//是否子商户
            $inputObj->SetAppid($wechatInfo['parent_appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['parent_mch_id']);//商户号
            $inputObj->SetSub_appid($wechatInfo['appid']);//子商户号公众账号ID
            $inputObj->SetSub_mch_id($wechatInfo['mch_id']);//子商户号
        } else { //普通商户
            $inputObj->SetAppid($wechatInfo['appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['mch_id']);//商户号
        }
        $inputObj->SetOut_refund_no($refundData['out_refund_no']);
        $inputObj->SetTotal_fee($refundData['total_fee'] * 100);
        $inputObj->SetRefund_fee($refundData['refund_fee'] * 100);
        $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
        $inputObj->SetKey($wechatInfo['parent_key']); //商户号密钥
        $inputObj->SetSign();//签名
        $xml = $inputObj->ToXml();
        $response = self::postXmlCurl($xml, $url, true,30);
        if ($response['status'] == 'S') {
            $wxPayResults = new WxPayResults();
            $result = $wxPayResults->Init($response['data']);
            wLog(date('Y-m-d H:i:s').' orderQuery result arr: '.var_export($result,true)."\r\n",'wechatPay');
            if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                return array('status' => 'S', 'data' => $result, 'message' => '查询成功');
            } else {
                return array('status' => 'F', 'message' => $result['err_code_des']);
            }
        } else {
            wLog(date('Y-m-d H:i:s').' orderQuery result error: '.var_export($response,true)."\r\n",'wechatPay');
            return array('status' => 'F', 'message' => $response['message']);
        }
    }

    /**
     * 查询订单
     * @param $accountId
     * @param $data
     * @return array $res
     */
    public function orderQuery($timeOut = 30)
    {
        //检测必填参数
        if (!$this->orderSn) {
            return array('stutus' => 'F', 'message' => '商户订单号不能为空！');
        }
        $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $this->accountId));
        if (!$wechatInfo) {
            return array('stutus' => 'F', 'message' => '微信配置信息不能为空');
        }

        vendor('Wechat.WxPayNew');
        $inputObj = new WxPayOrderQuery();
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";
        $inputObj->SetOut_trade_no($this->orderSn);
        if ($wechatInfo['is_special']) {//是否子商户
            $inputObj->SetAppid($wechatInfo['parent_appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['parent_mch_id']);//商户号
            $inputObj->SetSub_appid($wechatInfo['appid']);//子商户号公众账号ID
            $inputObj->SetSub_mch_id($wechatInfo['mch_id']);//子商户号
        } else { //普通商户
            $inputObj->SetAppid($wechatInfo['appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['mch_id']);//商户号
        }
        $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
        $inputObj->SetKey($wechatInfo['parent_key']); //商户号密钥
        $inputObj->SetSign();//签名
        $xml = $inputObj->ToXml();
        $response = self::postXmlCurl($xml, $url, false,$timeOut);
        if ($response['status'] == 'S') {
            $wxPayResults = new WxPayResults();
            $result = $wxPayResults->Init($response['data']);
            wLog(date('Y-m-d H:i:s').' orderQuery result arr: '.var_export($result,true)."\r\n",'wechatPay');
            if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                return array('status' => 'S', 'data' => $result, 'message' => '查询成功');
            } else {
                return array('status' => 'F', 'message' => $result['err_code_des']);
            }
        } else {
            wLog(date('Y-m-d H:i:s').' orderQuery result error: '.var_export($response,true)."\r\n",'wechatPay');
            return array('status' => 'F', 'message' => $response['message']);
        }
    }

    /**
     * 关闭订单
     * @param int $timeOut
     * @return array
     */
    public function orderClose($timeOut = 30)
    {
        //检测必填参数
        if (!$this->orderSn) {
            return array('stutus' => 'F', 'message' => '商户订单号不能为空！');
        }
        $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $this->accountId));
        if (!$wechatInfo) {
            return array('stutus' => 'F', 'message' => '微信配置信息不能为空');
        }

        vendor('Wechat.WxPayNew');
        $inputObj = new WxPayOrderClose();
        $url = "https://api.mch.weixin.qq.com/pay/closeorder";
        $inputObj->SetOut_trade_no($this->orderSn);
        if ($wechatInfo['is_special']) {//是否子商户
            $inputObj->SetAppid($wechatInfo['parent_appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['parent_mch_id']);//商户号
            $inputObj->SetSub_appid($wechatInfo['appid']);//子商户号公众账号ID
            $inputObj->SetSub_mch_id($wechatInfo['mch_id']);//子商户号
        } else { //普通商户
            $inputObj->SetAppid($wechatInfo['appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['mch_id']);//商户号
        }
        $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
        $inputObj->SetKey($wechatInfo['parent_key']); //商户号密钥
        $inputObj->SetSign();//签名
        $xml = $inputObj->ToXml();
        $response = self::postXmlCurl($xml, $url, false,$timeOut);
        if ($response['status'] == 'S') {
            $wxPayResults = new WxPayResults();
            $result = $wxPayResults->Init($response['data']);
            wLog(date('Y-m-d H:i:s').' orderClose result: '.var_export($result,true)."\r\n",'wechatPay');
            if ($result['return_code'] == 'SUCCESS') {
                return array('status' => 'S', 'data' => $result, 'message' => '查询成功');
            } else {
                return array('status' => 'F', 'message' => $result['err_code_des']);
            }
        } else {
            wLog(date('Y-m-d H:i:s').' orderClose error: '.var_export($response,true)."\r\n",'wechatPay');
            return array('status' => 'F', 'message' => $response['message']);
        }
    }

    /**
     * 撤销订单
     * @param $accountId
     * @param $data
     * @return array $res
     */
    public function orderReverse( $timeOut = 30,$is_again = 0)
    {
        //检测必填参数
        if (!$this->orderSn) {
            return array('stutus' => 'F', 'message' => '商户订单号不能为空！');
        }
        $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $this->accountId));
        if (!$wechatInfo) {
            return array('stutus' => 'F', 'message' => '微信配置信息不能为空');
        }

        $url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
        vendor('Wechat.WxPayNew');
        $inputObj = new WxPayReverse();
        $inputObj->SetOut_trade_no($this->orderSn);
        $this->sslcert_path = $wechatInfo['sslcert_path'];
        $this->sslkey_path = $wechatInfo['sslkey_path'];
        if ($wechatInfo['is_special']) {//是否子商户
            $inputObj->SetAppid($wechatInfo['parent_appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['parent_mch_id']);//商户号
            $inputObj->SetSub_appid($wechatInfo['appid']);//子商户号公众账号ID
            $inputObj->SetSub_mch_id($wechatInfo['mch_id']);//子商户号
        } else { //普通商户
            $inputObj->SetAppid($wechatInfo['appid']);//公众账号ID
            $inputObj->SetMch_id($wechatInfo['mch_id']);//商户号
        }
        $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
        $inputObj->SetKey($wechatInfo['parent_key']); //商户号密钥
        $inputObj->SetSign();//签名
        $xml = $inputObj->ToXml();
        $response = self::postXmlCurl($xml, $url, true, $timeOut);

        if ($response['status'] == 'S') {
            $wxPayResults = new WxPayResults();
            $result = $wxPayResults->Init($response['data']);
            wLog(date('Y-m-d H:i:s').' orderReverse result arr: '.var_export($result,true)."\r\n",'wechatPay');
            if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                if($result['recall'] == 'N') {
                    return array('status' => 'S', 'data' => $result, 'message' => '撤销成功');
                } else{
                    if($is_again == 1){
                        return array('status' => 'S', 'data' => $result, 'message' => '撤销失败');
                    } else {
                        sleep(1);
                        $this->orderReverse(30, 1);
                    }
                }
            } else {
                return array('status' => 'F', 'message' => $result['err_code_des']);
            }
        } else {
            wLog(date('Y-m-d H:i:s').' orderReverse result error: '.var_export($response,true)."\r\n",'wechatPay');
            return array('status' => 'F', 'message' => $response['message']);
        }
    }

    /**
     * 获得微信支付配置及订单数据
     * @param int $accountId 账号id
     * @param string $orderSn 订单号
     * @return array
     */
    public function getWechatPayData($accountId, $orderSn)
    {
        $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => $accountId));

        if (empty($wechatInfo)) {
            return array();
        }
        // 获取订单信息
        $orderInfo = $this->getInfoFromOrder($orderSn);
        $payData = array(
            'orderName' => $orderInfo['title'] ? $orderInfo['title'] : $this->title, // 订单名称
            'orderSn' => $orderInfo['order_sn'], // 订单编号
            'orderAmount' => $orderInfo['order_amount'], // 订单金额
            'is_special' => $wechatInfo['is_special']          // 是否是服务商支付，1:是，0:否
        );
        $openid = '';
        if (isset($orderInfo['openid']) && strlen($orderInfo['openid']) == 28) {
            $openid = $orderInfo['openid'];
        } elseif ($orderInfo['user_id']) {
            $openid = D('WechatUser')->where(array('user_id' => $orderInfo['user_id'], 'wechat_id' => $wechatInfo['wechat_id']))->getField('openid');
        }elseif ($orderInfo['wechat_user_id']) {
            $openid = D('WechatUser')->where(array('wechat_user_id' => $orderInfo['wechat_user_id'], 'wechat_id' => $wechatInfo['wechat_id']))->getField('openid');
        }

        /*if(!$openid){
            return array();
        }*/

        if ($wechatInfo['is_special'] == '1') {

            $data = array(
                'parentAppid' => $wechatInfo['parent_appid'],            // 母商户ID
                'parentAppsecret' => $wechatInfo['parent_appsecret'],    // 母商户密钥
                'parentMchId' => $wechatInfo['parent_mch_id'],            // 母商户商户ID
                'parentKey' => $wechatInfo['parent_key'],                // 母商户KEY
                'subOpenid' => $openid,                                 // 用户在子商户下的微信openid
                'subAppid' => $wechatInfo['appid'],                        // 子商户ID
                'subMchId' => $wechatInfo['mch_id']                      // 子商户商户ID
            );
        } else {
            $data = array(
                'appId' => $wechatInfo['appid'],           //appid
                'mchId' => $wechatInfo['mch_id'],          //商户号
                'parentKey' => $wechatInfo['parent_key'],    //支付密钥
                'openId' => $openid,                    //openid
            );
        }
        $returnData = array_merge($payData, $data);
        return $returnData;
    }

    /**
     *从订单号获取订单数据
     * @param string $orderSn
     * @return array
     */
    public function getInfoFromOrder($orderSn)
    {
        // 解析订单编号内的模块ID
        $moduleId = substr($orderSn, 14, 3);
        $moduleId = preg_replace('/^0+/', '', $moduleId);
        // 获取对应模块信息
        $moduleInfo = D('Module')->getByPk($moduleId);
        // 查询订单信息
        $orderInfo = D($moduleInfo['order_model_name'])->getByOrderSn($orderSn);

        return $orderInfo;
    }

    /**
     * 校验数据
     * @param array $data
     * @return array
     */
    public function verifyData($data)
    {
        //校验数据
        $verifyField = array();
        if ($data['is_special'] == 1) {
            $verifyField = array(
                'parentAppid',            // 母商户ID
                'parentMchId',            // 母商户商户ID
                'parentKey',            // 母商户KEY
                'subOpenid',            // 用户在子商户下的微信openid
                'subAppid',                // 子商户ID
                'subMchId',                // 子商户商户ID
                'orderName',            // 订单名称
                'orderSn',                // 订单编号
                'orderAmount',            // 订单金额
            );
        } elseif ($data['is_special'] == 0) {
            $verifyField = array(
                'appId',        // 商户的appid
                'mchId',        // 商户ID
                'parentKey',    // 商户支付密钥
                'openId',       // 用户在子商户下的微信openid
                'orderName',    // 订单名称
                'orderSn',      // 订单编号
                'orderAmount',  // 订单金额
            );
        }

        foreach ($verifyField as $value) {
            if (empty($data[$value])) {
                return array('status' => 'F', 'message' => $value . '不能为空');
            }
        }
    }

    /**
     *
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return 产生的随机字符串
     */
    public static function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
    private function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        //如果有配置代理这里就设置代理
        /*if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
            && WxPayConfig::CURL_PROXY_PORT != 0){
            curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
            curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        }*/
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if($useCert == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $this->sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $this->sslkey_path);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);

        //返回结果
        if($data){
            curl_close($ch);
            return array('status' => 'S','data' => $data);
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return array('status' => 'F','message' => "curl出错，错误码:$error");
        }
    }
}